package starter.config;

import cacheserial.CacheSerialQueueMonitor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import com.chtwm.pool.QbdPoolConfigurable;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 项目启动后
 *
 * @author Aimy
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "qbd.cache.serial", value = "enable", havingValue = "true")
public class QbdRedisInitListener implements ServletContextListener {

    @Autowired
    private CacheSerialConfig cacheSerialConfig;
    @Autowired
    private QbdPoolConfig qbdPoolConfig;

    @SneakyThrows
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //初始化线程池
        QbdPoolConfigurable.init(qbdPoolConfig.getPoolSize(), qbdPoolConfig.getTimeAlive(),
                qbdPoolConfig.getBlockQueueLength(), new CustomizableThreadFactory("QbdPool-"));

        //如果开启了缓存串行化，需要启动对应的监听线程
        if (cacheSerialConfig.isEnable()) {
            //启动监听任务
            CacheSerialQueueMonitor cacheSerialQueueMonitor =
                    new CacheSerialQueueMonitor(cacheSerialConfig.getMonitorThreadSize(), cacheSerialConfig.getQueueSize());
            //启动监听线程
            cacheSerialQueueMonitor.start();
        }

    }

    /**
     * 注册监听器
     *
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean() {
        ServletListenerRegistrationBean slrb = new ServletListenerRegistrationBean();
        slrb.setListener(this);
        return slrb;
    }
}
